<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(value) => emit('update:visible', value)"
    :title="isView ? '查看降等报废申请' : (formData ? '编辑降等报废申请' : '新增降等报废申请')"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="申请编号" prop="code">
            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-select
              v-model="form.reservoirName"
              placeholder="请选择水库"
              filterable
              style="width: 100%"
            >
              <el-option label="青山水库" value="青山水库" />
              <el-option label="白云水库" value="白云水库" />
              <el-option label="绿水水库" value="绿水水库" />
              <el-option label="蓝天水库" value="蓝天水库" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
              <el-option label="降等" value="downgrade" />
              <el-option label="报废" value="decommission" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人" prop="applicant">
            <el-input v-model="form.applicant" placeholder="请输入申请人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="申请日期" prop="applyDate">
            <el-date-picker
              v-model="form.applyDate"
              type="date"
              placeholder="请选择申请日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <el-input v-model="form.department" placeholder="请输入所属部门" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="申请中" value="applying" />
              <el-option label="审核中" value="reviewing" />
              <el-option label="已批准" value="approved" />
              <el-option label="已拒绝" value="rejected" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="原等级" prop="originalLevel">
            <el-select v-model="form.originalLevel" placeholder="请选择原等级" style="width: 100%">
              <el-option label="一等" value="一等" />
              <el-option label="二等" value="二等" />
              <el-option label="三等" value="三等" />
              <el-option label="四等" value="四等" />
              <el-option label="五等" value="五等" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标等级" prop="targetLevel">
            <el-select v-model="form.targetLevel" placeholder="请选择目标等级" style="width: 100%">
              <el-option label="二等" value="二等" />
              <el-option label="三等" value="三等" />
              <el-option label="四等" value="四等" />
              <el-option label="五等" value="五等" />
              <el-option label="报废" value="报废" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="申请原因" prop="reason">
        <el-input
          v-model="form.reason"
          type="textarea"
          :rows="3"
          placeholder="请输入申请原因"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewer">
            <el-input v-model="form.reviewer" placeholder="请输入审核人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核日期" prop="reviewDate">
            <el-date-picker
              v-model="form.reviewDate"
              type="date"
              placeholder="请选择审核日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="完成日期" prop="completionDate">
        <el-date-picker
          v-model="form.completionDate"
          type="date"
          placeholder="请选择完成日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  formData?: any
  isView?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: null,
  isView: false
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  id: null,
  code: '',
  reservoirName: '',
  type: '',
  applicant: '',
  applyDate: '',
  phone: '',
  department: '',
  status: 'applying',
  originalLevel: '',
  targetLevel: '',
  reason: '',
  reviewer: '',
  reviewDate: '',
  completionDate: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  reservoirName: [
    { required: true, message: '请选择水库名称', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  applicant: [
    { required: true, message: '请输入申请人', trigger: 'blur' }
  ],
  applyDate: [
    { required: true, message: '请选择申请日期', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' }
  ],
  originalLevel: [
    { required: true, message: '请选择原等级', trigger: 'change' }
  ],
  targetLevel: [
    { required: true, message: '请选择目标等级', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入申请原因', trigger: 'blur' }
  ]
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm()
    if (props.formData) {
      nextTick(() => {
        Object.assign(form, props.formData)
      })
    } else {
      // 新增时生成申请编号
      form.code = generateCode()
      form.applyDate = new Date().toISOString().split('T')[0]
    }
  }
})

// 生成申请编号
const generateCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `DC${year}${month}${day}${random}`
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    code: '',
    reservoirName: '',
    type: '',
    applicant: '',
    applyDate: '',
    phone: '',
    department: '',
    status: 'applying',
    originalLevel: '',
    targetLevel: '',
    reason: '',
    reviewer: '',
    reviewDate: '',
    completionDate: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 模拟API - 保存降等报废申请
const saveDecommission = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    return { success: true }
  } catch (error) {
    throw new Error('保存失败')
  }
}

// 模拟API - 更新降等报废申请
const updateDecommission = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    return { success: true }
  } catch (error) {
    throw new Error('更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const submitData = { ...form }
    
    if (props.formData) {
      await updateDecommission(submitData)
      ElMessage.success('更新成功')
    } else {
      await saveDecommission(submitData)
      ElMessage.success('保存成功')
    }
    
    emit('success')
    handleCancel()
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>